package com.dandandog.framework.faces.utils;

import cn.hutool.core.util.StrUtil;
import com.dandandog.framework.common.model.ITree;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @Author: JohnnyLiu
 * @Date: 2021/9/3 15:07
 */
public class TreeUtil {

    public static <T extends ITree> Multimap<String, T> parentMap(List<T> sources) {
        Multimap<String, T> idMap = ArrayListMultimap.create();
        sources.forEach(t -> idMap.put(StrUtil.isNotBlank(t.getParentId()) ? t.getParentId() : null, t));
        return idMap;
    }

//    public static <T extends ITree> List<T> getParent(String id, Collection<T> all) {
//        List<T> list = new ArrayList<>();
//        return all.stream().filter(m -> Objects.equals(m.getId(), id)).flatMap(t -> {
//            list.addAll(getParent(t.getParentId(), all));
//            return list.stream();
//        }).collect(Collectors.toList());
//    }


    public static <T extends ITree> void getParent(Set<String> idList, String id, List<T> all) {
        T t = all.stream().filter(m -> Objects.equals(m.getId(), id)).findFirst().orElse(null);
        if (t != null) {
            idList.add(t.getId());
            getParent(idList, t.getParentId(), all);
        }
    }


}
